import axios from 'axios';
import { ElLoading, ElMessage } from 'element-plus';
import type { AnyObj } from '@/Utils/type';
import router from '@/Router';
import { getCookie, handleLMSCategoryTree, onNoLogin } from '@/Utils/utils';
import qs from 'qs';

const instance = axios.create({
    timeout: Number(process.env.VITE_TIME_OUT) || 3000,
    baseURL: process.env.VITE_BASE_URL
});

export type ResponseType =
    | 'arraybuffer'
    | 'blob'
    | 'document'
    | 'json'
    | 'text'
    | 'stream';

/**
* @author Elliot
* @date 2023-04-18 17:45
* @description 通用请求函数
* @param url 请求url
* @param data 请求body参数，post的时候传
* @param query 请求url参数，get的时候传，post时可以加传
* @param method post | get
* @param errorToast 是否请求失败后显示错误提示
* @param contentTypeIsForm post时传，true"content-type"为"application/x-www-form-urlencoded"，false为"application/json"
* @param showLoading 是否显示loading，对应的是ElementUI的ElLoading.service参数，显示loading时一般传{}，使用默认参数
* @param headers 请求头
* @param timeout 请求超时的毫秒数
* @param baseURL 请求根路径
* @param codeNotSuccessResolve 请求返回的code != 0(请求失败)的时候，是否执行resolve(res)
*/
export default function request (
{
    url = '',
    data = {},
    query = {},
    method = 'post',
    errorToast = true,
    contentTypeIsForm = false,
    showLoading,
    headers = {},
    timeout = Number(process.env.VITE_TIME_OUT),
    baseURL = process.env.VITE_BASE_URL,
    getRes = false,
    responseType = 'json',
}:
{
    baseURL?: string; // 请求baseURL
    timeout?: number; // 请求超时的毫秒数
    url: string; // 请求url
    query?: AnyObj; // 请求url参数，get的时候传，post时可以加传
    data?: AnyObj | string | number; // 请求body参数，post的时候传
    headers?: AnyObj; // 请求头
    method?: "post" | "get"; // post | get
    errorToast?: Boolean; // 是否请求失败后显示错误提示
    contentTypeIsForm?: Boolean; // post时传，true"content-type"为"application/x-www-form-urlencoded"，false为"application/json"
    getRes?: Boolean; // 是否获取整个res
    showLoading?: { // 是否显示loading，对应的是ElementUI的ElLoading.service参数，显示loading时一般传{}，使用默认参数
        text?: string;
        lock?: Boolean;
        background?: string;
    };
    responseType?: ResponseType;
} = { url: '' }
) : Promise<any> {
    if (url === '') return Promise.reject({errorMsg: '请求失败'});
    let loading : null | { close: () => void } = null;
    if (showLoading) {
        loading = ElLoading.service({
            lock: showLoading.lock === false ? false : true,
            text: showLoading.text || '加载中...',
            background: showLoading.background || 'rgba(0, 0, 0, 0.7)',
            body: true
        });
    }
    if (method === 'post' && 'Content-Type' in headers === false) {
        if (contentTypeIsForm) {
            headers['Content-Type'] = 'application/x-www-form-urlencoded';
        } else {
            headers['Content-Type'] = 'application/json';
        }
    }
    headers.userId = getCookie("userId");
    headers.token = getCookie("token");
    // console.log('headers: ', headers);
    return new Promise(async (resolve, reject) => {
        try {
            const result = await instance.request({
                method,
                baseURL,
                params: query,
                data: contentTypeIsForm && data ? qs.stringify(data, {allowDots: true, arrayFormat: 'repeat'}) : data,
                headers,
                timeout,
                url,
                responseType,
                withCredentials: true
            });
            // console.log('result: ', result);
            loading && loading.close();
            const res = result.data;
            if (res.code == 5) {
                if (errorToast) {
                    showRequestError({res});
                }
                onNoLogin();
                reject(res);
            }
            if (responseType === 'json') {
                if (res) {
                    if (getRes) {
                        resolve(res);
                    } else {
                        resolve(res.data);
                    }
                } else {
                    if (errorToast) {
                        showRequestError({res});
                    }
                    if (getRes) {
                        resolve(res);
                    } else {
                        reject(res);
                    }
                }
            } else if (responseType === 'blob') {
                // console.log('result: ', result);
                // console.log('res: ', res);
                try {
                    const text = JSON.parse(await new Response(res).text());
                    if (errorToast) {
                        showRequestError({res: text});
                    }
                    reject(text);
                } catch (error) {
                    resolve(res);
                }
            }
        } catch (error) {
            console.warn('error: ', error);
            reject(error);
            loading && loading.close();
            if (errorToast) showRequestError({error});
        }
    });
};

// 请求失败时的提示
export const showRequestError = ({res, error} : {res?: AnyObj, error?: any} = {}) => {
    let errorMsg = '请求失败';
    if (res) {
        const code = res.code;
        errorMsg = res.errorMsg || res.msg;
        if (!errorMsg) {
            switch (code) {
                case 2:
                    errorMsg = '当前用户没有权限！';
                    break;
                case 30:
                    errorMsg = '请求资源无效，请联系管理员！';
                    break;
                case 1:
                    // errorMsg = '请重新登录';
                    router.push("/login").catch((error) => {
                        ElMessage.error(error);
                    });
                    return;
                default:
                    break;
            }
        }
        if (!errorMsg) {
            errorMsg = res.msg || res.errMsg || '请求失败'
        }
    } else if (error) {
        if (typeof error === 'string') {
            errorMsg = error;
        } else if (error.message && typeof error.message === 'string') {
            errorMsg = error.message;
        } else if (error.request && typeof error.request === 'object' && typeof error.request.statusText === 'string') {
            errorMsg = error.request.statusText;
        }
    }
    ElMessage({
        message: errorMsg,
        type: 'warning',
        grouping: true
    });
};

// 校验是否登录
export const verify = async () => {
    // const token = getCookie("token");
    // if (token) {
    //     if (router.currentRoute.value.path === '/login') {
    //         router.push({
    //             path: '/home'
    //         })
    //     }
    //     return token;
    // }
    // quit();
    // return false;
    return 'ajasd';
    // const data = await request({
    //     url: '/user/auth/verify',
    //     method: 'post'
    // });
    // if (!data.isLogin) {
    //     quit();
    //     return;
    // }
    // if (data?.user) {
    //     localStorage.setItem('user', JSON.stringify(data.user));
    //     useUserStore().saveInfo(data.user);
    // }
}

// 获取大纲树
export const getLMSCategoryTree = async () => {
    try {
        return (await request({
            url: '/lms/category/adminGetTree',
            method: 'post'
        }) || []).map(handleLMSCategoryTree)
    } catch (error) {
        
    }
};